// components/form-generator/index.js
import {formatTime} from "../../utils/util"
import Toast from '@vant/weapp/toast/toast';
const app = getApp()

// 由于父传子组件即使是对象也不会共享地址，所以这里暂时用app全局来代替
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        formList:{
            type:Object,
        },
        currentIndex:{
            type:Number,
            value:0
        },
    },
    options: {
        styleIsolation: 'shared'
    },
    /**
     * 组件的初始数据
     */
    data: {
        showSelectList:false,
        // 下拉选择的id与name
        selectName:"",
        selectId:"",
        // 输入的值
        inputValue:"",

        showDate:false,
        dateType:"datetime", //默认值为date，可选为date、time、year-month
        // 开始日期
        beginDate:"",
        // 开始格式化的日期
        beginDateFormat:"",
        // 结束日期
        endDate:"",
        // 结束格式化日期
        endDateFormat:"",
        // 是开始还是结束日期
        beginEnd:true,//true为开始时间
        // 当前的时间
        currentDate:Date.now(),
        // 时间
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if(type === 'day'){
                return `${value}日`
            }
            if(type === 'hour'){
                return `${value}时`
            }
            if(type === 'minute'){
                return `${value}分`
            }
            return value;
        },
        // 照片
        imgList:[],
        // 视频
        video:'',
        // 选择项
    },
    observers:{

    },
    lifetimes:{
        ready(){
            // 只有存在value才是编辑
            // 要注意这里实在ready里面，不能随着父页面该百年数据而重新执行，除非写在监听里面，但监听太卡，使用该组件的时候一定要
            // wx:if判断formList长度大于0才渲染
            let formListObj = this.data.formList[this.data.currentIndex]
            if(!formListObj.value) return
            switch(formListObj.fieldType){
                case 1:
                    this.setData({
                        inputValue:formListObj.value
                    })
                    break;
                case 2:
                    let fieldOptions = formListObj.fieldOptions
                    let ids = formListObj.value.split(",")
                    let selectedName = ""
                    ids.forEach(item=>{
                        let target = fieldOptions.find(item2=>item==item2.id)
                        target.selected = true
                        if(!selectedName){
                            selectedName = selectedName+target.name
                        }else{
                            selectedName = selectedName+","+target.name
                        }
                    })
                    this.setData({
                        selectedName:selectedName,
                        formList:this.data.formList,
                    })
                    break;
                case 3:
                    if(formListObj.multiFlag&&formListObj.value){
                        this.setData({
                            beginDateFormat:formListObj.value.split(",")[0],
                            endDateFormat:formListObj.value.split(",")[1]
                        })
                    }else if(!formListObj.value){
                        this.setData({
                            beginDateFormat:formListObj.value,
                        })
                    }
                    break;
                case 4:
                    this.setData({
                        imgList:formListObj.value
                    })
                    break;
                
                case 5:
                    this.setData({
                        video:formListObj.value
                    })
                    break;
                
            }
        }   

    },
    /**
     * 组件的方法列表
     */
    methods: {
        // 自定义事件传值回去
        // 删除
        delete(e){
            let prop = e.currentTarget.dataset.prop
            let formListObj = this.data.formList[this.data.currentIndex]
            let appFormListObj = app.globalData.formList[this.data.currentIndex]
            if(prop=="inputValue"){
                formListObj.value = ""
                appFormListObj.value = ""
                this.setData({
                    inputValue:""
                })

            }
            if(prop=='beginDate'&&formListObj.multiFlag){
                this.setData({
                    beginDate:"",
                    beginDateFormat:""
                })
                if(this.data.beginDateFormat){
                    formListObj.value = [this.data.beginDateFormat,this.data.beginDateFormat].join(",")
                    appFormListObj.value = [this.data.beginDateFormat,this.data.beginDateFormat].join(",")
                }else{
                    formListObj.value = ""
                    appFormListObj.value = ""
                }
            }

            if(prop=='endDate'&&formListObj.multiFlag){
                this.setData({
                    endDate:"",
                    endDateFormat:""
                })
                if(this.data.beginDateFormat){
                    formListObj.value = [this.data.beginDateFormat,this.data.beginDateFormat].join(",")
                    appFormListObj.value = [this.data.beginDateFormat,this.data.beginDateFormat].join(",")
                }else{
                    formListObj.value = ""
                    appFormListObj.value = ""
                }
            }
        },
        // 输入
        inputChange(e){
            this.setData({
                inputValue:e.detail.value
            }) 
            this.data.formList[this.data.currentIndex].value = e.detail.value
            app.globalData.formList[this.data.currentIndex].value = e.detail.value
            console.log(app.globalData.formList,180)
        },
        // 下拉选择
        selectTarget(e){
            let index = e.currentTarget.dataset.index
            let formListObj = this.data.formList[this.data.currentIndex]
            let fieldOptions =  this.data.formList[this.data.currentIndex].fieldOptions
            if(index||index===0){
                if(!formListObj.multiFlag){
                    // 不是多选
                    fieldOptions.forEach(item=>{
                        delete item.selected
                    })
                }

                if(fieldOptions[index].hasOwnProperty('selected')){
                    fieldOptions[index].selected = !fieldOptions[index].selected
                }else{
                    fieldOptions[index].selected = true
                }
                

                // let ids = list.filter(item=>item.selected).map(item=>item.id)
                let names =fieldOptions.filter(item=>item.selected).map(item=>item.name)
                let ids = fieldOptions.filter(item=>item.selected).map(item=>item.id)
                this.setData({
                    selectedId:ids.length>0?ids.join(","):'',
                    selectedName:names.length>0?names.join(","):'',
                    formList: this.data.formList,
                })  
                formListObj.value = this.data.selectedId
                app.globalData.formList[this.data.currentIndex].value = this.data.selectedId
            }
        },
        // 清除全部选择
        clearAllSelect(){
             this.data.formList[this.data.currentIndex].fieldOptions.forEach(item=>{
                delete item.selected
            })
            this.data.formList[this.data.currentIndex].value = ""
            app.globalData.formList[this.data.currentIndex].value = ""

            this.setData({
                formList: this.data.formList,
                selectedName:"",
            })
            
        },
        // 显示下拉选择
        showSelectPopup(){
            this.setData({
                showSelectList:true
            })
        },
        // 关闭下拉选择
        closeSelectPopup(){
            this.setData({
                showSelectList:false,
            })
        },
        // 时间选择
        dateChange(e){
            let value = formatTime(e.detail,this.data.dateType)
            let formListObj = this.data.formList[this.data.currentIndex]
            console.log(this.data.beginDate)
            if(this.data.beginEnd){
                if(this.data.endDate&&e.detail>this.data.endDate){
                    console.log(e.detail,this.data.beginDate,this.data.endDate)
                    Toast.fail("开始时间不能大于结束时间")
                    return
                }
                this.setData({
                    beginDate:e.detail,
                    beginDateFormat:value
                })
            }else{
                if(this.data.beginDate&&this.data.beginDate>e.detail){
                    Toast.fail("结束时间不能小于开始时间")
                    return
                }
                this.setData({
                    endDate:e.detail,
                    endDateFormat:value
                })
            }


            this.setData({
                showDate:false,
                currentDatetime:e.detail
            })

            formListObj.value=this.data.beginDateFormat
            app.globalData.formList[this.data.currentIndex].value = this.data.beginDateFormat
            if(this.data.endDateFormat){
                formListObj.value  = this.data.beginDateFormat+','+this.data.endDateFormat
                app.globalData.formList[this.data.currentIndex].value = this.data.beginDateFormat+','+this.data.endDateFormat
            }
            
        },
        // 打开时间选择弹框
        showDatePopup(e){
            let flag = e.currentTarget.dataset.flag
            this.setData({
                beginEnd:flag?true:false,
                showDate:true,
            })
    
            if(this.data.beginEnd&&this.data.beginDate){
                console.log("开始")
                this.setData({
                    currentDate:this.data.beginDate
                })
            }else if(!this.data.beginEnd&&this.data.endDate){
                console.log("结束")
                this.setData({
                    currentDate:this.data.endDate
                })
            }else{
                this.setData(
                    this.setData({
                        currentDate:Date.now()
                    })
                )
            }
        },
        //关闭时间弹框
        closeDatePopup(){
            this.setData({
                showDate:false
            })
        },
        // 添加图片
        addImg(){
            wx.chooseImage({
                mediaType: "image",
                sizeType:['original', 'compressed'],
                sourceType:["album","camera"],
                success:res=>{
                    let list = res.tempFiles.map(item=>item.path)
                    let formListObj = this.data.formList[this.data.currentIndex]

                    if(this.data.imgList.concat(list).length>5){
                        Toast.fail("图片最多不超过5张")
                        return
                    }
                    this.setData({
                        imgList:this.data.imgList.concat(list)
                    })
                    formListObj.value = []
                    app.globalData.formList[this.data.currentIndex].value =[]
                    this.data.imgList.forEach((item,index)=>{
                        let tempUrlReg =/^https/
                        if(!tempUrlReg.test(item)){
                            // 临时文件需要转base64
                            wx.getFileSystemManager().readFile({
                                filePath:this.data.imgList[index],
                                encoding:"base64",
                                success:(res)=>{
                                    formListObj.value.push(res.data)
                                    app.globalData.formList[this.data.currentIndex].value.push(res.data)
                                    console.log(app.globalData.formList,362)
                                }
                            })
                        }else{
                            formListObj.value.push(item)
                            app.globalData.formList[this.data.currentIndex].value.push(item)
                        }
                    })
                },
                fail:err=>{
      
                }
            })
        },
        // 删除图片
        deleteImg(e){
            let index = e.currentTarget.dataset.index
            let formListObj =  this.data.formList[this.data.currentIndex]
            this.data.imgList.splice(index,1)
            formListObj.value.splice(index,1)
            app.globalData.formList[this.data.currentIndex].value.splice(index,1)
            this.setData({
                imgList:this.data.imgList
            })
            if(formListObj.value.length==0){
                //如果为0那么就赋值为空字符串
                formListObj.value = ""
                app.globalData.formList[this.data.currentIndex].value = ""
            }
        },
        // 预览图片
         previewImg(e){
            wx.previewImage({
              urls: this.data.imgList,
              current:e.currentTarget.dataset.item
            })
        },
        // 选择视频
        addVideo(){
            wx.chooseMedia({
                count: 1,
                mediaType: ['video'],
                sourceType: ['album', 'camera'],
                maxDuration: 30,
                camera: 'back',
                success:res=> {
                    let tempFilePath = res.tempFiles[0].tempFilePath
                    this.setData({
                        video:tempFilePath
                    })
                    wx.getFileSystemManager().readFile({
                        filePath:tempFilePath,
                        encoding:"base64",
                        success:(res)=>{
                            this.data.formList[this.data.currentIndex].value = res.data
                            app.globalData.formList[this.data.currentIndex].value = res.data
                        }
                    })
                }
              })
        },
        // 删除视频
        deleteVideo(){
            this.setData({
                video:''
            })
            this.data.formList[this.data.currentIndex].value = ""
            app.globalData.formList[this.data.currentIndex].value = ""
        },
    }
})
